Create SQLAlchemy Classes
Let’s learn about how to create SQLAlchemy classes with coding examples.
We'll cover the following
For part of our test suite, we’ll need to create and populate the test database with our initial data. However, we also need to define somewhere the tables that will be contained in the database. This is where SQLAlchemy’s ORM comes into play since we define the tables in terms of Python objects.
Updated requriments#
We’ve already installed the SQLAlchemy and psycopg2 when we added them into the prod.txt requirements file:
Let’s discuss the code#
Let’s break down the code above, piece by piece.
In lines 1—2, we import many things from the SQLAlchemy package to set up the database and create the table. Keep in mind that SQLAlchemy has a declarative approach, so we need to instantiate the object Base and then use it as a starting point to declare the tables and objects in line 4.
From line 7 to line 16, the Room class represents the rooms in the database. It’s important to understand that this isn’t the class we use in our business logic but the class that defines the table in the SQL database that we use to map the Room entity. The structure of this class is thus dictated by the needs of the storage layer and not by the use cases layer.
We may want, for instance, to store longitude and latitude in a JSON field, allowing for easier extendibility and not changing the domain model’s definition. The two classes almost overlap in the simple case of our Rent-o-Matic project, but this is generally not the case.
This means that we have to keep the storage and the domain levels in sync. We also need to manage migrations on our own. We can use tools like Alembic, but the migrations won’t come directly from domain model changes.
Label Integration Tests
Orchestration Management